package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.User;
import cn.wolfcode.luowowo.service.IUserService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登陆拦截器
public class LoginInterceptor implements HandlerInterceptor{
    //注入用户业务接口
    @Autowired
    private IUserService userService;

    //当前登录用户信息
    private  User currentUser;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("URI"+request.getRequestURI());
        //System.out.println("请求类型"+request.getMethod());

        //获取token
        String token = request.getHeader("token");
        //获取当前登陆用户(放在前面是为了即使请求的方法不需要校验登录,也去重置一次登录有效时间)
        if (StringUtils.hasLength(token)){
            currentUser = userService.getCurrentUser(token);
        }

        //非请求映射方法放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取当前请求映射方法对象
        HandlerMethod md =(HandlerMethod) handler;
        RequireLogin annotation = md.getMethod().getAnnotation(RequireLogin.class);
        //判断当前请求映射方法是否有贴需要校验登录的注解
        if (annotation == null){
            //没贴,不用校验,放行
            return true;
        }
        //校验登录
        if (currentUser == null){//未登录,不放行
            //通过response响应返回未登录信息
            //设置响应格式json和编码utf-8
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }else {//已经登录,放行
            return true;
        }

    }
}
